﻿$(function () {
    window.progressDialog = new ProgressDialog();
    window.infoDialog = new InfoDialog();
    window.ajaxClass = new AjaxClass();    
    window.AutoComplete = new AutoComplete();
    window.resizeFlexiGrid = new ResizeFlexiGrid("#MainTable .flexigrid", "#List1", "#MainTable .flexigrid .bDiv", ["#TitleTR", "#SearchTR", "#PageTR", "#MainTable .flexigrid .hDiv"], 4, 4);
    window.activityItem = new ActivityItem("activityItem", "#ItemHTML", "#AddTable .AIcon div.Icon", "AddTable", "<tr><td class=\"Unit\">", "</td></tr>", AddItemEnd, null, false);
    window.flexiGrid = new FlexiGrid("flexiGrid", "List1", "ListTD", "PageTR", "SearchTR", "resizeFlexiGrid", [
            { display: '自动编号', name: 'AutoID', width: 50, sortable: true, align: 'left', hide: true },
            { display: '产品货号', name: 'pd_id', width: 50, sortable: true, align: 'left', hide: false },
            { display: '产品名称', name: 'pd_cn_name', width: 300, sortable: true, align: 'left', hide: false },
            { display: '产品规格', name: 'pd_cn_spec', width: 300, sortable: true, align: 'left', hide: false },
            { display: '单位', name: 'uom', width: 25, sortable: true, align: 'left', hide: false },
            { display: '对方编码', name: 'ct_pd_id', width: 100, sortable: false, align: 'left', hide: false },
            { display: '操作', name: 'Operation', width: 80, sortable: false, align: 'left', hide: false }
        ], "产品列表", "AutoID", "desc", "", false, null, null);
    window.resizeFlexiGrid.Resize("resizeFlexiGrid");
    $("#ButtonBack").button({ icons: { primary: "ui-icon-arrowreturnthick-1-w"} }).click(function () { window.location.href = JsonOriginal.UrlReferrer; });
    $("#ButtonAddInput").button({ icons: { primary: "ui-icon-pencil"} }).click(function () { $("#AddTable").html(""); window.activityItem.AddItem(); $("#AddDialog").dialog("open"); $("#AddDialog").css("overflow-x", "hidden"); });
    if (HasntPermission("添加产品")) { $("#ButtonAddSelect, #ButtonAddInput").button({ disabled: true }); }

    /* 选择产品部分 --------------------------------------------------------------------------------------------*/

    $("#ButtonAddSelect").button({ icons: { primary: "ui-icon-search"} }).click(function () {
        if (window.flexiGridSelect == undefined) {
            window.resizeFlexiGridSelect = new ResizeFlexiGrid("", "#List2", "#STable .flexigrid .bDiv", ["#SelectTitleTR", "#SelectSearchTR", "#SelectPageTR", "#STable .flexigrid .hDiv"], 4, 4);
            window.flexiGridSelect = new FlexiGrid("flexiGridSelect", "List2", "SelectListTD", "SelectPageTR", "SelectSearchTR", "resizeFlexiGridSelect", [
                { display: '自动编号', name: 'AutoID', width: 50, sortable: true, align: 'left', hide: true },
                { display: '货号', name: 'pd_id', width: 50, sortable: true, align: 'left', hide: false },
                { display: '名称', name: 'pd_cn_name', width: 150, sortable: true, align: 'left', hide: false },
                { display: '规格', name: 'pd_cn_spec', width: 100, sortable: true, align: 'left', hide: false },
                { display: '单位', name: 'uom', width: 25, sortable: true, align: 'left', hide: true },
                { display: '操作', name: 'Operation', width: 30, sortable: false, align: 'left', hide: false }
            ], "产品选择列表", "AutoID", "desc", "", true, "FPNL RC PZT PNI", SetSelectLink);
            window.resizeFlexiGridSelect.Resize("resizeFlexiGridSelect");

            window.resizeFlexiGridCheck = new ResizeFlexiGrid("", "#List3", "#CTable .flexigrid .bDiv", ["#SelectTitleTR", "#CheckSearchTR", "#CTable .flexigrid .hDiv"], 4, 4);
            window.flexiGridCheck = new FlexiGrid("flexiGridCheck", "List3", "CheckListTD", null, null, null, [
                { display: '自动编号', name: 'AutoID', width: 50, sortable: false, align: 'left', hide: true },
                { display: '货号', name: 'pd_id', width: 50, sortable: false, align: 'left', hide: false },
                { display: '名称', name: 'pd_cn_name', width: 150, sortable: false, align: 'left', hide: false },
                { display: '规格', name: 'pd_cn_spec', width: 100, sortable: false, align: 'left', hide: false },
                { display: '单位', name: 'uom', width: 25, sortable: false, align: 'left', hide: true },
                { display: '对方编码', name: 'cn_pd_id', width: 100, sortable: false, align: 'left', hide: false },
                { display: '操作', name: 'Operation', width: 30, sortable: false, align: 'left', hide: false }
            ], null, "AutoID", "desc", "", true, null, null);
            window.resizeFlexiGridCheck.Resize("resizeFlexiGridCheck");
            $("#CheckBack").button({ icons: { primary: "ui-icon-arrowreturnthick-1-w"} }).click(function () { $("#SelectTable").css("display", "none"); $("#MainTable").removeAttr("style"); window.resizeFlexiGrid.Height(); });
            $("#CheckSave").button({ icons: { primary: "ui-icon-disk"} }).click(function () {
                if ($("#List3 tr").size() > 0) {
                    var checkOK = true; var Temp, Index;
                    $("#List3 tr").each(function (index, element) {
                        if ($(element).find("input:first").val() == "") {
                            checkOK = false;
                        } else {
                            Temp = $(element).find("input:first").val(); Index = index;
                            $("#List3 tr").each(function (index, element) { if ($(element).find("input:first").val() == Temp && index != Index) { checkOK = false; } });
                        }
                    });
                    if (checkOK) {
                        var TempJson = new Array();
                        var ActionOperations = new Array();
                        $("#List3 tr").each(function (index, element) {
                            TempJson.push([{ "OperationKey": "检查重复", "Parameters": { "@ct_pd_id": $(element).find("input:first").val()}}]);
                            ActionOperations.push({ "OperationKey": "添加产品", "Parameters": { "@AutoID": $(element).find("div:first").attr("title"), "@ct_pd_id": $(element).find("input:first").val()} });
                        });
                        TempJson.push(ActionOperations);
                        TempJson.push([{ "OperationKey": window.flexiGrid.listName, "Parameters": null, "JsonParameter": "{\"记录控制\":[{\"开始记录\":0,\"返回数量\":" + window.flexiGrid.PageSize + "}]}"}]);
                        var JsonSend = { "ActionParameters": JSON.stringify(TempJson) };
                        window.ajaxClass.AjaxSubmit(JsonOriginal.UrlAction, JsonSend, "", "window.flexiGrid.Refresh(data.ReturnData[data.ReturnData.length-1], \"AutoID\", \"desc\", \"\"); $('#SelectTable').css('display', 'none'); $('#MainTable').removeAttr('style'); window.resizeFlexiGrid.Height();", "", false, true);
                    } else {
                        infoDialog.OpenDialog("对方编码必须填写，并且不能重复！", "Alert");
                    }
                } else {
                    $("#SelectTable").css("display", "none"); $("#MainTable").removeAttr("style"); window.resizeFlexiGrid.Height();
                }
            });
        } else {
            window.flexiGridSelect.searchKey = "";
            window.flexiGridSelect.sortName = "AutoID";
            window.flexiGridSelect.sortOrderk = "desc";
            $("#List3").html("");
        }
        window.flexiGridSelect.LoadData("$('#MainTable').css('display', 'none');$('#SelectTable').removeAttr('style');", "", "", null, null);
    });

    /* 更新产品对话框 --------------------------------------------------------------------------------------------*/

    $("#UpdateDialog").dialog({
        autoOpen: false,
        resizable: false,
        height: 236,
        width: 541,
        modal: true,
        zIndex: 1000,
        buttons: {
            保存: function () {
                if ($("#ct_pd_id").val() != "") {
                    var JsonSend = { "ActionParameters": JSON.stringify([[{ "OperationKey": "检查重复", "Parameters": { "@ct_pd_id": $("#ct_pd_id").val()}}], [{ "OperationKey": "修改产品", "Parameters": { "@AutoID": $("#AutoID").val(), "@ct_pd_id ": $("#ct_pd_id").val()}}], [{ "OperationKey": window.flexiGrid.listName, "Parameters": { "@SortName": window.flexiGrid.sortName, "@SortOrder": window.flexiGrid.sortOrder, "@SearchKey": window.flexiGrid.searchKey }, "JsonParameter": "{\"记录控制\":[{\"开始记录\":" + ((window.flexiGrid.PageNum - 1) * window.flexiGrid.PageSize) + ",\"返回数量\":" + window.flexiGrid.PageSize + "}]}"}]]) };
                    window.ajaxClass.AjaxSubmit(JsonOriginal.UrlAction, JsonSend, "", "window.flexiGrid.Refresh(data.ReturnData[data.ReturnData.length-1], \"AutoID\", \"desc\", \"\"); $('#UpdateDialog').dialog('close');", "", false, true);
                } else {
                    infoDialog.OpenDialog('对方编码必须填写！', 'Alert');
                }
            },
            取消: function () {
                $(this).dialog("close");
            }
        }
    });

    /* 添加产品对话框 --------------------------------------------------------------------------------------------*/

    $("#AddDialog").dialog({
        autoOpen: false,
        resizable: false,
        height: 578,
        width: 883,
        modal: true,
        zIndex: 1000,
        buttons: {
            保存: function () {
                var checkOK = true; var Temp, Index;
                $("#AddTable input.Required").each(function (index, element) {
                    if ($(this).val() == "") {
                        checkOK = false;
                    } else {
                        Temp = $(this).val(); Index = index;
                        $("#AddTable input.Required").each(function (index, element) { if ($(this).val() == Temp && index != Index) { checkOK = false; } });
                    }
                });
                if (checkOK) {
                    var TempJson = new Array();
                    var ActionOperations = new Array();
                    $("#AddTable .Unit").each(function (index, element) {
                        if ($(element).find("input[name='AutoID']").val() != "") {
                            TempJson.push([{ "OperationKey": "检查重复", "Parameters": { "@ct_pd_id": $(element).find("input[name='ct_pd_id']").val()}}]);
                            ActionOperations.push({ "OperationKey": "添加产品", "Parameters": { "@AutoID": $(element).find("input[name='AutoID']").val(), "@ct_pd_id": $(element).find("input[name='ct_pd_id']").val()} });
                        }
                    });
                    TempJson.push(ActionOperations);
                    TempJson.push([{ "OperationKey": window.flexiGrid.listName, "Parameters": null, "JsonParameter": "{\"记录控制\":[{\"开始记录\":0,\"返回数量\":" + window.flexiGrid.PageSize + "}]}"}]);
                    var JsonSend = { "ActionParameters": JSON.stringify(TempJson) };
                    window.ajaxClass.AjaxSubmit(JsonOriginal.UrlAction, JsonSend, "", "window.flexiGrid.Refresh(data.ReturnData[data.ReturnData.length-1]); $('#AddDialog').dialog('close');", "", false, true);
                } else {
                    infoDialog.OpenDialog("对方编码必须填写，并且不能重复！", "Alert");
                }
            },
            取消: function () {
                $(this).dialog("close");
            }
        }
    });
});

/* 选择产品方法 --------------------------------------------------------------------------------------------*/

function SelectProduct(AutoID) {
    var TR = $("#List2 tr td[abbr='AutoID'] div[title='" + AutoID + "']:first").parent().parent();
    var HTML = TR.html().replace(/sorted/ig, "");
    var Insert = HTML.toLowerCase().lastIndexOf("<td ");
    TR_Html = HTML.substr(0, Insert) + "<td><div style=\"text-align: left; width: 107px; padding:3px 0 0 3px; \"><input class=\"Required\" type=\"text\" name=\"ct_pd_id\" style=\"text-align: left; width: 97px; \" /></div></td>" + HTML.substr(Insert).replace(/SelectProduct/, "CancelProduct").replace(/选择/, "取消");
    TR.find("a").css("visibility", "hidden");
    $("#List3").append("<tr>" + TR_Html + "</tr>");
    window.resizeFlexiGridCheck.Height();
    $("#List3 tr:odd").addClass("erow");
}

function CancelProduct(AutoID) {
    $("#List3 tr td[abbr='AutoID'] div[title='" + AutoID + "']:first").parent().parent().remove();
    $("#List2 tr td[abbr='AutoID'] div[title='" + AutoID + "']:first").parent().parent().find("a").css("visibility", "visible");
    window.resizeFlexiGridCheck.Height();
}

function SetSelectLink() {
    $("#List2 tr").each(function (index, element) {
        if ($("#List3 tr td[abbr='AutoID'] div[title='" + $(element).find("div:first").attr("title") + "']:first").size() > 0) {
            $(element).find("a:last").css("visibility", "hidden");
        }
    });
}

/* 设置自动完成 --------------------------------------------------------------------------------------------*/

function SelectAutoComplete(event, ui) {
    var Value = ui.item.label.substring(1, ui.item.label.length - 1).split("], [");
    $("#AddTable input.Select.AutoComplete").autocomplete("destroy");
    $("#AddTable input[name='AutoID'].AutoComplete").val(Value[0]).removeClass("AutoComplete");
    $("#AddTable input[name='pd_id'].AutoComplete").val(Value[1]).attr("title", Value[1]).attr("readonly", "readonly").removeClass("AutoComplete").removeClass("Select");
    $("#AddTable input[name='pd_cn_name'].AutoComplete").val(Value[2]).attr("title", Value[2]).attr("readonly", "readonly").removeClass("AutoComplete").removeClass("Select");
    $("#AddTable input[name='pd_cn_spec'].AutoComplete").val(Value[3]).attr("title", Value[3]).attr("readonly", "readonly").removeClass("AutoComplete").removeClass("Select");
    $("#AddTable input[name='uom'].AutoComplete").val(Value[4]).attr("readonly", "readonly").removeClass("AutoComplete");
    $("#AddTable input[name='ct_pd_id']").addClass("Required").removeAttr("readonly");
    window.activityItem.AddItem();
}

function AddItemEnd() {
    $("#AddTable input[name='ct_pd_id'].Required:last").focus();
    if ($("#AddTable .Unit").size() > 5) {
        window.AutoComplete.SetAutoComplete("#AddTable input.Select.AutoComplete", { my: "left bottom", at: "left top", of: "#AddTable input[name='pd_id'].Select.AutoComplete", collision: "none" }, "264px", "738px", "481px", SelectAutoComplete, "AutoComplete");
    } else {
        window.AutoComplete.SetAutoComplete("#AddTable input.Select.AutoComplete", { my: "left top", at: "left bottom", of: "#AddTable input[name='pd_id'].Select.AutoComplete", collision: "none" }, "264px", "738px", "481px", SelectAutoComplete, "AutoComplete");
    }
}

/* 页面初始化填充 --------------------------------------------------------------------------------------------*/

function ShowUpdateDialog(AutoID) {
    var DataList = JsonOriginal.Operations["产品列表"].OperationData.rows;
    for (var i = 0; i < DataList.length; i++) {
        if (AutoID == DataList[i].cell[0]) {
            $("#AutoID").val(DataList[i].cell[0]);
            $("#pd_id").val($("<div>" + DataList[i].cell[1] + "</div>").text());
            $("#pd_id").attr("title", $("<div>" + DataList[i].cell[1] + "</div>").text());
            $("#pd_cn_name").val($("<div>" + DataList[i].cell[2] + "</div>").text());
            $("#pd_cn_name").attr("title", $("<div>" + DataList[i].cell[2] + "</div>").text());
            $("#pd_cn_spec").val($("<div>" + DataList[i].cell[3] + "</div>").text());
            $("#pd_cn_spec").attr("title", $("<div>" + DataList[i].cell[3] + "</div>").text());
            $("#uom").val($("<div>" + DataList[i].cell[4] + "</div>").text());
            $("#uom").attr("title", $("<div>" + DataList[i].cell[4] + "</div>").text());
            $("#ct_pd_id").val($("<div>" + DataList[i].cell[5] + "</div>").text());
            $("#ct_pd_id").attr("title", $("<div>" + DataList[i].cell[5] + "</div>").text());
        }
    }
    $("#UpdateDialog").dialog("open");
    $("#ct_pd_id").focus();
}